package com.genersoft.iot.vmp.conf;

import com.alibaba.fastjson.JSONArray;
import com.genersoft.iot.vmp.common.ResultCode;
import com.genersoft.iot.vmp.gb28181.bean.Device;
import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
import com.genersoft.iot.vmp.gb28181.utils.DateUtil;
import com.genersoft.iot.vmp.service.ILogService;
import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
import com.genersoft.iot.vmp.storager.IVideoManagerStorager;
import com.genersoft.iot.vmp.storager.dao.dto.LogDto;
import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
import com.genersoft.iot.vmp.vmanager.gb28181.device.DeviceQuery;
import com.genersoft.iot.vmp.vmanager.gb28181.device.bean.Guard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import javax.sip.message.Response;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class WVPTimerTask {
    private final static Logger logger = LoggerFactory.getLogger(WVPTimerTask.class);


//    @Autowired
//    private IRedisCatchStorage redisCatchStorage;
//
//    @Autowired
//    private SipConfig sipConfig;
//
//    @Autowired
//    private MediaConfig mediaConfig;

    @Autowired
    private IVideoManagerStorager storager;

    @Autowired
    private DeferredResultHolder resultHolder;
    @Autowired
    private SIPCommander cmder;
    @Autowired
    private ILogService logService;
    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    // @Scheduled(cron="0 0/5 * * * ? ")   //每5分钟执行一次。。测试之后改成每1小时
    @Scheduled(cron="0 0 0/1 * * ? ")   //每5分钟执行一次。。测试之后改成每1小时
    public void execute(){
        String hours = DateUtil.formatDate(new Date(),"HH");

        guard(hours);
        resetGuard(hours);


//        redisCatchStorage.updateWVPInfo();
    }


    public void guard( String hours){
        List<Device> deviceList=  storager.getGuardDevices(hours);
        DeferredResult<ResponseEntity<String>> result = new DeferredResult(Long.valueOf(3000L));
        long start = System.currentTimeMillis();
        JSONArray params = new JSONArray();
        for (Device deviceInfo : deviceList){
            String deviceId = deviceInfo.getDeviceId();
            Guard guard = new Guard();
            guard.setDeviceId(deviceId);
            guard.setGuardCmdStr("SetGuard");
            Device device = this.storager.queryVideoDevice(deviceId);
            params.add(deviceId);
            this.cmder.humanGuardCmd(device, guard, event -> {
                Response response = event.getResponse();
                logger.error(String.format("布防/撤防操作失败，错误码： %s, %s", new Object[] { Integer.valueOf(response.getStatusCode()), response.getReasonPhrase() }));
            });
            result.onTimeout(() -> {

//                RequestMessage msg = new RequestMessage();
                logger.error(String.format("布防/撤防操作超时： %s", deviceId));

            });
            //布防
            deviceInfo.setGuardStatus(1);
            storager.updateDevice(deviceInfo);

        }
        saveLog(params,start,"SetGuard");
    }

    public void resetGuard( String hours){
        List<Device> deviceList=  storager.getResetGuardDevices(hours);
        DeferredResult<ResponseEntity<String>> result = new DeferredResult(Long.valueOf(3000L));
        long start = System.currentTimeMillis();
        JSONArray params = new JSONArray();
        for (Device deviceInfo : deviceList){
            String deviceId = deviceInfo.getDeviceId();
            Guard guard = new Guard();
            guard.setDeviceId(deviceId);
            guard.setGuardCmdStr("ResetGuard");
            Device device = this.storager.queryVideoDevice(deviceId);
            params.add(deviceId);

            this.cmder.humanGuardCmd(device, guard, event -> {
                Response response = event.getResponse();
                logger.error(String.format("布防/撤防操作失败，错误码： %s, %s", new Object[] { Integer.valueOf(response.getStatusCode()), response.getReasonPhrase() }));
            });
            result.onTimeout(() -> {

//                RequestMessage msg = new RequestMessage();
                logger.error(String.format("布防/撤防操作超时： %s", deviceId));

            });
            //撤防
            deviceInfo.setGuardStatus(0);
            storager.updateDevice(deviceInfo);

        }
        saveLog(params,start,"ResetGuard");

    }

    /**
     *
     * @param params 请求参数
     * @param start 请求开始时间
     */
    private void saveLog(JSONArray params,long start,String type){
        if(params.size() <1){
            return;
        }

        LogDto logDto = new LogDto();
        if("SetGuard".equals(type)) {
            logDto.setName("[设备控制] 定时布防");
        }else if("ResetGuard".equals(type)){
            logDto.setName("[设备控制] 定时撤防");
        }else{
            logDto.setName("没有可执行命令");
        }
        logDto.setUsername("system");
        logDto.setAddress("127.0.0.1");
        logDto.setResult("200 OK");
        logDto.setTiming(System.currentTimeMillis() - start);
        logDto.setType("GET");
        logDto.setUri("TimerTask");
        logDto.setCreateTime(format.format(System.currentTimeMillis()));
        logDto.setRequestParam(params.toString());
        logService.add(logDto);
    }
}
